<template>
  <el-dialog width="700px" title="上传文件" v-model="props.visible" append-to-body @close="close">
    <el-upload
      ref="upload"
      :headers="uploadHeaders"
      class="upload-demo"
      :action="url"
      :limit="1"
      :on-exceed="handleExceed"
      :auto-upload="false"
       :data="{ updateSupport: true }"
      :before-upload="beforeUpload"
      :on-success="xlsxSuccess"
      :on-error="handleError"
      accept=".xlsx,.xls"
      :on-change="handleChange"
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
      <el-button class="ml-3" type="success" @click="submitUpload">
        上传至服务器
      </el-button>
      <template #tip>
        <div class="el-upload__tip text-red">
          只能选择xlsx或xls格式文件，其他格式文件将无法选择
        </div>
      </template>
    </el-upload>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { genFileId } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  url: {
    type: String,
    default: ''
  },
  parentFunction: {
    type: Function
  }
})
const emit = defineEmits(['parentFunction'])
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

const fileList = ref<UploadRawFile[]>([])
const upload = ref<UploadInstance>()

const close = () => {
  upload.value!.clearFiles()
  emit('parentFunction')
}
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const handleError = (error: Error, file: UploadRawFile, fileList: UploadRawFile[]) => {
  ElMessage.error('文件上传失败')
  upload.value!.clearFiles()
}

const xlsxSuccess = (response: any, file: any, fileList: any) => {
  if (response.code === 200) {
    ElMessage.success('上传成功')
    upload.value!.clearFiles()
    emit('parentFunction')
  } else {
    ElMessage.error(response.msg)
    upload.value!.clearFiles()
    file.status = 'error' // 设置文件状态为错误
  }
}

const uploadHeaders = {
  Authorization: 'Bearer ' + getToken()
}
// 允许的文件扩展名
const allowedExtensions = ['.xlsx', '.xls']

// 处理文件选择变化
const handleChange = (file: UploadRawFile) => {
  const extension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'))
  if (!allowedExtensions.includes(extension)) {
    ElMessage.error('请选择 xlsx 或 xls 格式的文件！')
    // 清除不符合要求的文件
    upload.value!.clearFiles()
    return false
  }
  return true
}

// 上传前校验文件类型
const beforeUpload = (file: UploadRawFile) => {
  fileList.value = []
  fileList.value.push(file)
  const extension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'))
  if (!allowedExtensions.includes(extension)) {
    ElMessage.error('只能上传 xlsx 或 xls 格式的文件！')
    return false
  }
  return true
}

const submitUpload = () => {
  upload.value!.submit()
}
</script>
